<template>
	<view
		v-if="visibleSync" 
		class="uni-drawer"
	>
		<view class="uni-drawer__mask" :style="{opacity: opacity}" @tap.stop.prevent="masktap" ></view>
		<view 
			class="uni-drawer__content" 
			:style="{transition: transition,transform: transform}"
			@touchstart="touchstart"
			@touchmove="touchmove"
			@touchend="touchend"
		>
			<slot></slot>
		</view>
	</view>
</template>

<script>
	export default {
		created(){
			const res = uni.getSystemInfoSync();
			this.drawerW = res.windowWidth * 0.8;
		},
		name: 'uni-drawer',
		props: {
			visible: {
				type: Boolean,
				default: false
			}
		},
		data() {
			return {
				visibleSync: this.visible,
				hasTran: false,
				startX: '',
				newTranslate: 0,
				drawerW: 0,
				transform: '',
				opacity: 0,
				starttouch: false,
			}
		},
		computed: {
			transition() {
				if(this.hasTran) {
					return 'all 0.3s ease-out';
				} else {
					return 'none';
				}
			}
		},
		watch: {
			visible(bool) {
				if (bool) {
					this.visibleSync = bool;
					this.hasTran = true;
					this.transform = 'translateX(-100%)';
					this.opacity = 0.6;
					setTimeout(() => {
						this.transform = 'translateX(0)';
						this.opacity = 0.6;
					}, 100);
				} else {
					this.hasTran = true;
					this.transform = 'translateX(-100%)';
					this.opacity = 0;
					setTimeout(() => {
						this.visibleSync = bool;
					}, 300);
				}
			}
		},
		methods: {
			masktap() {
				this.$emit('close');
			},
			touchstart(e) {
				this.hasTran = false;
				this.startX = e.changedTouches[0].pageX;
			},
			touchmove(e) {
				if (!this.hasTran) {
					var x = e.changedTouches[0].pageX;
					var newTranX = x - this.startX;
					if (newTranX > 0) {
						newTranX = 0;
					}
					if (newTranX < -this.drawerW) {
						newTranX = -this.drawerW;
					}
					this.transform = `translateX(${2 * newTranX}rpx)`;
				}
			},
			touchend(e) {
				this.hasTran = true;
				var x = e.changedTouches[0].pageX;
				if (x < this.startX && (this.startX - x) >= this.drawerW * 0.2) {
					this.$emit('close');
				} else {
					this.transform = 'translateX(0)';
					this.opacity = 0.6;
				}
			}
		}
	}
</script>

<style lang="scss">
	$drawer-width:80%;

	.uni-drawer {
		display: block;
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		overflow: hidden;
		z-index: 1001;
		height: 100%;
		&__mask {
			display: block;
			opacity: 0.6;
			position: absolute;
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;
			background: $uni-bg-color-mask;
			transition: opacity 0.3s;
		}
		&__content {
			display: block;
			position: absolute;
			top: 0;
			left: 0;
			width: $drawer-width;
			height: 100%;
			background: $uni-bg-color;
			transition: all 0.3s ease-out;
			transform: translatex(-100%);
		}
	}
</style>
